package com.yxq.mdt.app.modules.personal.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ToastUtils;
import com.orhanobut.hawk.Hawk;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.modules.personal.bean.AddressBean;
import com.yxq.mdt.app.modules.personal.bean.AddressListBean;
import com.yxq.mdt.app.modules.personal.model.AddressModel;
import com.yxq.mdt.app.modules.personal.presenter.AddressPresenter;
import com.yxq.mdt.app.modules.personal.presenter.IAddressContract;
import com.yxq.mdt.app.utils.StringUtils;
import com.yxq.mdt.app.widgets.CustomAddressPicker;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.qqtheme.framework.entity.City;
import cn.qqtheme.framework.entity.County;
import cn.qqtheme.framework.entity.Province;

/**
 * @author L
 * @time
 * @describe 新增收货地址
 */
public class AddressManagerAddActivity extends BaseActivity<AddressPresenter> implements IAddressContract.View {


    @BindView(R.id.address_et_name)
    EditText addressEtName;
    @BindView(R.id.address_et_phone)
    EditText addressEtPhone;
    @BindView(R.id.address_tv_area)
    TextView addressTvArea;
    @BindView(R.id.address_et_detail)
    EditText addressEtDetail;
    @BindView(R.id.address_checkbox_default)
    CheckBox addressCheckboxDefault;
    @BindView(R.id.address_btn_add)
    Button addressBtnAdd;
    private boolean hideProvince = false;
    private boolean hideCounty = false;
    private String selectedProvince = "", selectedCity = "", selectedCounty = "";
    ArrayList<Province> provinceArrayList = new ArrayList<>();
    String addressId;
    String selectedProvinceId = "", selectedCityId = "", selectedCountyId = "";
    AddressListBean.ListBean addressListBean;

    @Override
    public int getLayoutId() {
        return R.layout.activity_address_manager_add;
    }

    @Override
    public void initView() {
        mPresenter = new AddressPresenter(this, new AddressModel());
        addressListBean = (AddressListBean.ListBean) getIntent().getSerializableExtra("data");
        if (addressListBean != null) {
            addressId = addressListBean.getId();
            bindView();
        }
        addressCheckboxDefault.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                setDefault(addressId);
            }
        });
    }

    /**
     * 设置默认地址
     */
    private void setDefault(String id) {
        if (!TextUtils.isEmpty(id)) {
            mPresenter.setDefault(id);
        }
    }

    /**
     * 设置数据
     */
    private void bindView() {
        addressEtName.setText(addressListBean.getName());
        addressEtPhone.setText(addressListBean.getMobile());
        addressEtDetail.setText(addressListBean.getDetail());
        addressCheckboxDefault.setChecked(addressListBean.getIs_default() == 1);
        selectedProvince = addressListBean.getProvince();
        selectedProvinceId = addressListBean.getProvince_id();
        selectedCity = addressListBean.getCity();
        selectedCityId = addressListBean.getCity_id();
        selectedCounty = addressListBean.getDistrict();
        selectedCountyId = addressListBean.getDistrict_id();
        addressTvArea.setText(String.format("%s %s %s", addressListBean.getProvince(), addressListBean.getCity(), addressListBean.getDistrict()));
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        //加载缓存的区域数据
        List<AddressBean> addressBeanList = null;
        String address = Hawk.get("addressList", null);
        if (address != null) {
            addressBeanList = JSON.parseArray(address, AddressBean.class);
        }
        if (addressBeanList != null) {
            parseAddressList(addressBeanList);
        }
        mPresenter.district();
    }

    @OnClick({R.id.address_tv_area, R.id.address_btn_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.address_tv_area:
                addressPickView();
                break;
            case R.id.address_btn_add:
                addAddress();
                break;
        }
    }

    /**
     * 保存地址
     */
    private void addAddress() {
        if (addressEtName.getText().toString().trim().length() == 0) {
            ToastUtils.showShort("请填写收货人姓名");
            return;
        }
        if (addressEtPhone.getText().toString().trim().length() == 0) {
            ToastUtils.showShort("请填写收货人手机号");
            return;
        }
        if (!StringUtils.isMobileExact(addressEtPhone.getText())) {
            ToastUtils.showShort("请输入合法的手机号码");
            return;
        }
        if (addressTvArea.getText().toString().trim().length() == 0) {
            ToastUtils.showShort("请选择配送地址");
            return;
        }
        if (addressEtDetail.getText().toString().trim().length() == 0) {
            ToastUtils.showShort("请填写详细地址");
            return;
        }
        showLoadingDialog();
        mPresenter.save(addressId, addressEtName.getText().toString(), addressEtPhone.getText().toString(), selectedProvinceId, selectedCityId, selectedCountyId, addressEtDetail.getText().toString());
    }

    /**
     * 选择地址弹出框
     */
    private void addressPickView() {
        if (provinceArrayList.size() == 0) {
            showLoadingDialog();
            return;
        }
        CustomAddressPicker picker = new CustomAddressPicker(this, provinceArrayList);

        /** 显示几列 **/
        picker.setHideProvince(hideProvince);
        picker.setHideCounty(hideCounty);

        /** 标题区域 **/
        picker.setTopBackgroundColor(getResources().getColor(R.color.white));//设置标题背景颜色
        picker.setTopHeight(60);//设置顶部标题栏高度（单位为dp）

        picker.setCancelText("取消");
        picker.setCancelTextSize(14);
        picker.setCancelTextColor(getResources().getColor(R.color.color_font_black));//设置顶部标题栏取消按钮文字颜色
        picker.setCancelVisible(true);//设置左边按钮是否显示

        picker.setTitleText("所在地区");//标题栏
        picker.setTitleTextSize(14);//标题栏大小
        picker.setTitleTextColor(getResources().getColor(R.color.color_font_black));//设置所在区域颜色

        picker.setSubmitText("完成");//设置标题右边文字
        picker.setSubmitTextSize(14);//设置完成按钮大小
        picker.setSubmitTextColor(getResources().getColor(R.color.color_font_black));//设置完成按钮颜色

        /**  标题与列表的分割线 **/
        picker.setTopLineColor(getResources().getColor(R.color.white));
        picker.setTopLineVisible(true);
        picker.setTopLineHeight(10);

        /** 列表区域 **/
        picker.setTextSize(14);//字体大小
        picker.setTextColor(getResources().getColor(R.color.black));//设置省市县字体滚动颜色
        picker.setDividerColor(getResources().getColor(R.color.white));//设置分割线的颜色
        picker.setLineSpaceMultiplier(4);
        /** 弹框消失的设置 **/
        picker.setCancelable(true);//false：必须选择后弹框才消失，true：点击框外可弹框消失


        /** 列的比重 **/
        if (hideCounty) {
            picker.setColumnWeight(0.8f, 1.0f);
        } else if (hideProvince) {
            picker.setColumnWeight(1.0f, 0.8f);
        } else {
            picker.setColumnWeight(1.0f, 1.0f, 1.0f);
        }

        picker.setSelectedItem(selectedProvince, selectedCity, selectedCounty);//设置默认
        picker.setOnAddressPickListener((Province province, City city, County county) -> {
            selectedProvinceId = province.getAreaId();
            selectedProvince = province.getAreaName();
            selectedCityId = city.getAreaId();
            selectedCity = city.getAreaName();
            selectedCountyId = county.getAreaId();
            selectedCounty = county.getAreaName();
            addressTvArea.setText(String.format("%s %s %s", province.getAreaName(), city.getAreaName(), county.getAreaName()));
        });
        picker.show();
    }

    @Override
    public void onLoadSuccess(List<AddressBean> addressBeanList) {
        //缓存区域数据
        Hawk.put("addressList", JSON.toJSONString(addressBeanList));
        parseAddressList(addressBeanList);
        hideLoadingDialog();
    }

    /**
     * 处理地区数据
     *
     * @param addressBeanList
     */
    private void parseAddressList(List<AddressBean> addressBeanList) {
        for (AddressBean addressBean : addressBeanList) {
            Province province = new Province(addressBean.getId() + "", addressBean.getName());
            List<AddressBean.ListBeanX> listBeanXES = addressBean.getList();
            List<City> cityList = new ArrayList<>();
            for (AddressBean.ListBeanX cityBean : listBeanXES) {
                City city = new City(cityBean.getId() + "", cityBean.getName());
                List<AddressBean.ListBeanX.ListBean> listBeanList = cityBean.getList();
                List<County> countyList = new ArrayList<>();
                for (AddressBean.ListBeanX.ListBean CountyBean : listBeanList) {
                    countyList.add(new County(CountyBean.getId() + "", CountyBean.getName()));
                }
                city.setCounties(countyList);
                cityList.add(city);
            }
            province.setCities(cityList);
            provinceArrayList.add(province);
        }
    }

    @Override
    public void onLoadFailed(String msg) {
        hideLoadingDialog();
        ToastUtils.showShort(msg);
    }

    @Override
    public void onLoadListSuccess(AddressListBean addressListBean) {

    }

    @Override
    public void onLoadListFailed(String msg) {

    }

    @Override
    public void onSaveSuccess(AddressListBean.ListBean result) {
        hideLoadingDialog();
        addressListBean = result;
        addressListBean.setAddress(addressListBean.getProvince()+addressListBean.getCity()+addressListBean.getDistrict()+addressListBean.getDetail());
        //如果新添加地址 设置默认操作
        if (TextUtils.isEmpty(addressId) && addressCheckboxDefault.isChecked()) {
            setDefault(result.getId());
            return;
        }
//        ToastUtils.showShort("保存成功");
        if (getIntent().getStringExtra("from") != null) {
            Intent data = new Intent();
            data.putExtra("data", addressListBean);
            setResult(RESULT_OK, data);
        } else {
            setResult(RESULT_OK);
        }
        finish();
    }

    @Override
    protected void back() {
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void onSaveFailed(String msg) {
        hideLoadingDialog();
        ToastUtils.showShort(msg);
    }

    @Override
    public void onDeleteSuccess(int position, String result) {

    }

    @Override
    public void onDeleteFailed(String msg) {

    }

    @Override
    public void onSetDefaultSuccess(String result) {
        if (TextUtils.isEmpty(addressId)) {
//            ToastUtils.showShort("保存成功");
            if (getIntent().getStringExtra("from") != null) {
                Intent data = new Intent();
                addressListBean.setAddress(addressListBean.getProvince()+addressListBean.getCity()+addressListBean.getDistrict()+addressListBean.getDetail());
                data.putExtra("data", addressListBean);
                setResult(RESULT_OK, data);
            } else {
                setResult(RESULT_OK);
            }
            finish();
        } else {
            ToastUtils.showShort(result);
        }
    }

    @Override
    public void onSetDefaultFailed(String msg) {
        ToastUtils.showShort(msg);
    }
}
